package com.iye.puretennis.activity;

import android.app.Activity;
import android.app.LocalActivityManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.*;
import android.view.animation.AnimationUtils;
import android.widget.*;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.MultiViewGroup;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.DBManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/12.
 */
public class TabsActivity extends TabActivity {
        private LayoutInflater layoutInflater;
        DBManager dbManager;

        TabHost tabs;
        private GestureDetector gestureDetector;
        View.OnTouchListener gestureListener;
        int currentView = 0;
        private static int maxTabIndex = 3;
        public static int screenWidth  ;
        public static int scrrenHeight ;
        private ViewPager mPager;
        // Tab页面列表
        private List<View> listViews;
        private LocalActivityManager mLocalActivityManager;
        private final Context context = TabsActivity.this;

    /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            DisplayMetrics metric = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metric);
            screenWidth = metric.widthPixels ;
            scrrenHeight = metric.heightPixels;
            System.out.println("screenWidth * scrrenHeight --->" + screenWidth + " * " +scrrenHeight);


            setContentView(R.layout.bottomtabs);
            dbManager = new DBManager(this);
            layoutInflater = getLayoutInflater();
            tabs = getTabHost();
            initTabs();
            // 注意下面这段
            mLocalActivityManager =new LocalActivityManager(this,true);
            mLocalActivityManager.dispatchCreate(savedInstanceState);
//            tabs.setup(mLocalActivityManager);
            //tabhost改变同样改变ViewPager的内容
            tabs.setOnTabChangedListener(new OnTabChangeListener() {

                @Override
                public void onTabChanged(String tabId) {
                    mPager.setCurrentItem(Integer.parseInt(tabId));
                }
            });
            initViewPager();
            tabs.setOnTabChangedListener(tabChangeListener);
//
//            gestureDetector = new GestureDetector(new MyGestureDetector());
//            gestureListener = new View.OnTouchListener() {
//                @Override
//                public boolean onTouch(View v, MotionEvent event) {
//                    return gestureDetector.onTouchEvent(event);
//                }
//            };
//            tabs.setOnTouchListener(gestureListener);
//            tabs.setLongClickable(true);
        }



    private void initViewPager() {
        mPager = (ViewPager) findViewById(R.id.vPager);
        listViews = new ArrayList<View>();
        MyPagerAdapter mpAdapter = new MyPagerAdapter(listViews);
        Intent intent = new Intent(context, MyGroupsActivity.class);
        listViews.add(getView("A", intent));
        Intent intent2 = new Intent(context, MyFriendsActivity.class);
        listViews.add(getView("B", intent2));
        Intent intent3 = new Intent(context, LoginPageActivity.class);
        listViews.add(getView("C", intent3));
        Intent intent4 = new Intent(context, ProfileActivity.class);
        listViews.add(getView("D", intent4));
        mPager.setAdapter(mpAdapter);
        mPager.setCurrentItem(0);
        mPager.setOnPageChangeListener(new MyOnPageChangeListener());
    }

    public class MyPagerAdapter extends PagerAdapter {
        public List<View> mListViews;

        public MyPagerAdapter(List<View> mListViews) {
            this.mListViews = mListViews;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(mListViews.get(arg1));
        }

        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public int getCount() {
            return mListViews.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(mListViews.get(arg1), 0);
            return mListViews.get(arg1);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 获取当前活动的Activity实例

        Activity subActivity =mLocalActivityManager.getCurrentActivity();
        //subActivity = mLocalActivityManager.getActivity("TabsActivity");
        //判断是否实现返回值接口
        if (subActivity instanceof TabHostResultListener) {
            //获取返回值接口实例
            TabHostResultListener listener = (TabHostResultListener) subActivity;
            //转发请求到子Activity
            listener.onTabActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }



    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    tabs.setCurrentTab(0);
                    break;
                case 1:
                    tabs.setCurrentTab(1);
                    break;
                case 2:
                    tabs.setCurrentTab(2);
                    break;
                case 3:
                    tabs.setCurrentTab(3);
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    private View getView(String id,Intent intent)
    {
        return mLocalActivityManager.startActivity(id, intent).getDecorView();
    }

    // 左右滑动刚好页面也有滑动效果
    class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {


        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            return super.onFling(e1,e2,velocityX,velocityY);
        }
//            try {
//                if (Math.abs(e1.getY() - e2.getY()) > Constant.SWIPE_MAX_OFF_PATH)
//                    return false;
//                // right to left swipe
//                if (e1.getX() - e2.getX() > Constant.SWIPE_MIN_DISTANCE
//                        && Math.abs(velocityX) > Constant.SWIPE_THRESHOLD_VELOCITY) {//从右向左滑动
//                    Log.i("test", "right");
//                    if (currentView == maxTabIndex) {
//                        currentView = 0;
//                    } else {
//                        currentView++;
//                    }
//                    //animation
//
//                    tabs.getCurrentView().startAnimation(AnimationUtils.loadAnimation(TabsActivity.this,R.anim.push_left_out));
//                    tabs.setCurrentTab(currentView);
//                    tabs.getCurrentView().startAnimation(AnimationUtils.loadAnimation(TabsActivity.this,R.anim.push_left_in));
//                } else if (e2.getX() - e1.getX() > Constant.SWIPE_MIN_DISTANCE
//                        && Math.abs(velocityX) > Constant.SWIPE_THRESHOLD_VELOCITY) {//从左向右滑动
//                    Log.i("test", "left");
//                    if (currentView == 0) {
//                        currentView = maxTabIndex;
//                    } else {
//                        currentView--;
//                    }
//                    //animation
//                    tabs.getCurrentView().startAnimation(AnimationUtils.loadAnimation(TabsActivity.this,R.anim.push_right_out));
//                    tabs.setCurrentTab(currentView);
//                    tabs.getCurrentView().startAnimation(AnimationUtils.loadAnimation(TabsActivity.this,R.anim.push_right_in));
//                }
//            } catch (Exception e) {
//            }
//            return true;
//        }
    }
    private void initTabs() {

        //设置Tab1
        TabSpec tab1 = tabs.newTabSpec("0");
        tab1.setIndicator(getTabItemView(this.getString(R.string.group),R.drawable.tab_group));      // 设置tab1的名称
        Intent groupIntent = new Intent(this, MyGroupsActivity.class);
        groupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab1.setContent(groupIntent);    // 关联控件
        tabs.addTab(tab1);                // 添加tab1


        //设置Tab2
        TabSpec tab2 = tabs.newTabSpec("1");
        tab2.setIndicator(getTabItemView(this.getString(R.string.friends),R.drawable.tab_friends));
        Intent friendsIntent = new Intent(this, MyFriendsActivity.class);
        friendsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab2.setContent(friendsIntent);
        tabs.addTab(tab2);

        //设置Tab3
        TabSpec tab3 = tabs.newTabSpec("2");
        tab3.setIndicator(getTabItemView(this.getString(R.string.appointment),R.drawable.tab_appointments));
        Intent appointmentIntent = new Intent(this, LoginActivity.class);
        appointmentIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab3.setContent(appointmentIntent);
        tabs.addTab(tab3);

        //设置Tab4
        TabSpec tab4 = tabs.newTabSpec("3");
        tab4.setIndicator(getTabItemView(this.getString(R.string.me),R.drawable.tab_me));
        Intent meIntent = new Intent(this, ProfileActivity.class);
        meIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab4.setContent(meIntent);
        tabs.addTab(tab4);
        //select first
        tabs.setCurrentTab(0);
        tabs.getCurrentTabView().setBackgroundColor(getResources().getColor(R.color.orangered));
    }

    private OnTabChangeListener tabChangeListener  = new OnTabChangeListener() {

            @Override
            public void onTabChanged(String tabId) {
                int j = tabs.getTabWidget().getTabCount();
                for (int i = 0; i < j ; i++){
                    if(tabs.getCurrentTab() == i){
                        tabs.getTabWidget().getChildTabViewAt(i).setEnabled(false);
                        tabs.getTabWidget().getChildTabViewAt(i).setBackgroundColor(getResources().getColor(R.color.orangered));
                    }else{
                        if(tabs.getTabWidget().getChildTabViewAt(i) != null){
                            tabs.getTabWidget().getChildTabViewAt(i).setEnabled(true);
                            tabs.getTabWidget().getChildTabViewAt(i).setBackgroundColor(getResources().getColor(R.color.peru));
                        }
                    }
                }
            }
        };

    /**

     * 给Tab按钮设置图标和文字

     */

    private View getTabItemView(String title,int imageId){

        View view = layoutInflater.inflate(R.layout.tab_item, null);
        TextView textView = (TextView) view.findViewById(R.id.textview);

        textView.setText(title);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);

        imageView.setImageResource(imageId);

        return view;

    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            exitApp();
            return true;
        }else{
            return super.dispatchKeyEvent(event);
        }
    }

    private long exitTime = 0;

    public void exitApp()
    {
        if ((System.currentTimeMillis() - exitTime) > 2000)
        {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else
        {
            dbManager.logout();
            this.finish();
        }
    }
}